# 读取文件
from dotenv import load_dotenv
from fastapi import APIRouter, Depends
import os
from dotenv import load_dotenv
from common.log import get_logger
# 数据库相关
from sqlalchemy.orm import Session
from common.database import get_db
from app.models.operator import Operator
# HTTP请求响应相关
from common.http import error_response, ok_response, show_response
from app.schemas.platform import SendResourcesRequest, SendAgentMerchantsRequest

logger = get_logger("server")
router = APIRouter(tags=["web"])
router.prefix = "/v2"
CREDIT_CODE = os.getenv("CREDIT_CODE")
load_dotenv()


@router.post("/show_agent_merchants")
async def show_agent_merchants(payload: SendAgentMerchantsRequest, db: Session = Depends(get_db)):  # 写死了先交个差

    operators = os.getenv("CREDIT_CODE")
    if not operators:
        return error_response(code=404, message="Unknown Credit Code.")
    else:
        temp_json_data = [
            {
                "creditCode": "91440300326639824D",
                "userName": "深圳技术大学体育馆",
                "operator": "张三",
                "operatorTel1": "186XdXXX1234",
                "operatorTel2": "0755-34782011",
                "operatorAddress": "深圳市坪山区石井街道田头社区兰田路3002号",
            },
            {
                "creditCode": "91440300978635846D",
                "userName": "深圳技术大学大数据与互联网学院",
                "operator": "李四",
                "operatorTel1": "186XXXX1234",
                "operatorTel2": "0755-34782011",
                "operatorAddress": "深圳市坪山区石井街道田头社区兰田路3002号",
            },
            {
                "creditCode": "91440300978635811D",
                "userName": "深圳技术大学E0食堂",
                "operator": "王五",
                "operatorTel1": "186XXXX1234",
                "operatorTel2": "0755-34782011",
                "operatorAddress": "深圳市坪山区石井街道田头社区兰田路3002号",
            },
            {
                "creditCode": "91440300978635822D",
                "userName": "深圳技术大学C5教学楼",
                "operator": "甲",
                "operatorTel1": "186XXXX1234",
                "operatorTel2": "0755-34782011",
                "operatorAddress": "深圳市坪山区石井街道田头社区兰田路3002号",
            },
            {
                "creditCode": "91440300978635833D",
                "userName": "深圳技术大学C4会堂",
                "operator": "乙",
                "operatorTel1": "186XXXX1234",
                "operatorTel2": "0755-34782011",
                "operatorAddress": "深圳市坪山区石井街道田头社区兰田路3002号",
            },
            {
                "creditCode": "91440300978635844D",
                "userName": "深圳技术大学E3北区宿舍",
                "operator": "丙",
                "operatorTel1": "186XXXX1234",
                "operatorTel2": "0755-34782011",
                "operatorAddress": "深圳市坪山区石井街道田头社区兰田路3002号",
            },
        ]

        """
        展示代理用户
        """
        temp_agent_merchants = []
        # results = db.scalars(select(Operator)).all()
        # for item in temp_json_data:
        #     temp_agent_merchants.append(
        #         {
        #             "creditCode": json_data.credit_code,
        #             "userName": json_data.user_name,
        #             "operator": json_data.operator,
        #             "operatorTel1": json_data.operator_tel1,
        #             "operatorTel2": json_data.operator_tel2,
        #             "operatorAddress": json_data.operator_address
        #         }
        #     )
        return ok_response(data=temp_json_data)


@router.post("/show_resources")
async def show_resources(payload: SendResourcesRequest, db: Session = Depends(get_db)):
    json_datas = [{
        "resourceId": "qianhai#01",
        "resourceName": "前海科技#1",
        "resourceType": 1,
        "subType": "101",
        "responseType": "1",
        "responseLevel": "响应一级",
        "resourceState": "2",
        "maxAdjustablePower": 100,
        "increaseRate": 100,
        "decreaseRate": 100,
        "listingNum": "0164536613",
        "ratedcapacity": 5.0,
        "ratedpower": 4.2,
        "deviceNum": 3,
        "ratedVoltage": 0.38,
        "latitude": 22.660535,
        "address": "深圳技术大学",
        "longitude": 114.047473,
        "parentResouceId": 0
    }]
    operator = os.getenv("CREDIT_CODE")
    if not operator:
        return {"page": payload.page, "totalPage": 1, "resource": "NULL"}

    # offset_size = page_size * (page - 1)
    # find_sql = select(Resource).filter_by(operator_id=operator.id)
    # total_count = db.scalars(
    #     select(func.count("*")).select_from(Resource).filter_by(operator_id=operator.id)
    # ).one()
    # logger.info("total_count = ", total_count)
    # results = db.scalars(find_sql.offset(offset_size).limit(page_size)).all()
    ret_data = []
    """
    responseLevel
    响应时间级别，
    响应一级（响应时间≤1秒以内达到响应目标）：1 
    响应二级（1秒＜响应时间≤1分钟以内达到响应目标）：2 
    响应三级（ 1分钟＜响应时间≤15分钟以内达到响应目标）：3
    响应四级（15分钟＜响应时间≤30分钟以内达到响应目标） ：4
    响应五级（30分钟＜响应时间≤2小时以内达到响应目标）：5 
    响应六级（2小时＜响应时间≤24小时以内达到响应目标）：6  
    响应七级（≥24小时以内达到响应目标）：7 
    """
    # for json_data in json_datas:
    #     ret_data.append(
    #         {
    #             "resourceId": json_data.resourceId,
    #             "resourceName": json_data.resource_name,
    #             "resourceType": json_data.resource_type,
    #             "responseType": 1,  # 响应方式，传编码值（1：自动响应，0：人工响应）
    #             "resourceState": result.resource_state,  # 资源状态，传编码值（2表示测试，3表示投运，4表示退役，5表示停机）
    #             "maxAdjustablePower": result.max_adjustable_power,
    #             "increaseRate": 0,  # 最大上升速率（kW/min）
    #             "decreaseRate": 0,  # 最大下降速率（kW/min）
    #             "responseLevel": 1,  # 响应时间级别
    #             "deviceNum": 1,  # 该resourceID下挂设备数量(充电站填充电桩数量，换电站填电池数量，建筑楼宇填空调主机数量，铁塔基站/分布式光伏及其他均填1)
    #             "longitude": json_data.longitude,
    #             "latitude": json_data.latitude,
    #             "address": "深圳技术大学",  # 用电地址
    #             "parentSourceId": 0
    #         }
    #     )
    return {
        "page": payload.page,
        "totalPage": payload.pageSize,
        "resources": json_datas[:payload.pageSize],
    }
